// pages/shoppingcart/shoppingcart.js
const app=getApp()
const share = require('../../components/utils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [
      {value: 'USA', name: '美国'},
      {value: 'CHN', name: '中国', checked: 'true'},
      {value: 'BRA', name: '巴西'},
      {value: 'JPN', name: '日本'},
      {value: 'ENG', name: '英国'},
      {value: 'FRA', name: '法国'}
    ],
    isselect:false,
    imgurl:app.globalData.Imageurl,
    isselectshop:0,
    shoptotal:0,
    pageNo:1,
    pageSize:10,
    isfeli:false,
    isloding:false,
    pagemax:0,
    goodsCarLists:[],
    scrollleft:0,
    lefts:100,
    //是否重重置页面
    isrefresh:1,
    refresh:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

      wx.showLoading({
        title: '正在加载',
        mask:true
      })
      

  },
  upper(e) {
    console.log(e)
  },

  lower(e) {
    console.log(e)
  },
  bindscrolltoupper(e){
    console.log(e)
    var datalist=this.data.goodsCarLists
    datalist.forEach(element => {
      if(element.id==e.currentTarget.dataset.id){
        element.scrollleft=0
      }
    })
    this.setData({
      goodsCarLists:datalist
    })
   
  },
  bindscrolltolower(e){
    // console.log(e)
    var datalist=this.data.goodsCarLists
    datalist.forEach(element => {
      if(element.id==e.currentTarget.dataset.id){
        element.scrollleft=100
      }else{
        element.scrollleft=0
      }
    })
    this.setData({
      goodsCarLists:datalist
    })
  },

  scrollToTop() {
    this.setAction({
      scrollTop: 0
    })
  },
  //获取购物车列表
  getGoodsCadList(){
    var t=this
    wx.request({
      url: app.globalData.Interfaceurl + 'getGoodsCarPage',
      method: "post",
      header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
          userId: app.globalData.userId,
          pageNo:t.data.pageNo,
          pageSize:t.data.pageSize,
      },
      success: res => {
          console.log(res)
          if(res.data.page.list.length>0){
            t.setData({
              isempty:false,
              ishave:true,  
            })
                // 分页
              if(t.data.pageNo<Math.ceil(res.data.page.count/res.data.page.pageSize)){
                t.setData({
                  isfeli:false,
                  isloding:true,
                })
              }else{
                t.setData({
                  isfeli:true,
                  isloding:false,
                })
              }
          }else{
            t.setData({
              isempty:true,
              ishave:false,
              isfeli:false,
              isloding:false,
            })
          }
           res.data.page.list.forEach(element => {
            element.checked=false
            element.scrollleft=0
          });
          if(t.data.goodsCarLists==[]){
            t.setData({
              goodsCarLists:res.data.page.list,
              pagemax:Math.ceil(res.data.page.count/res.data.page.pageSize)
              
            })
          }else{
            t.setData({
              goodsCarLists:t.data.goodsCarLists.concat(res.data.page.list),
              pagemax:Math.ceil(res.data.page.count/res.data.page.pageSize)
            })
          }
          
          // t.setData({
          //   isloadcomplete:false
          // })
          wx.hideLoading()
          console.log(t.data.goodsCarLists)
          
      }
     })
    
  },

  tap() {
    for (let i = 0; i < order.length; ++i) {
      if (order[i] === this.data.toView) {
        this.setData({
          toView: order[i + 1],
          scrollTop: (i + 1) * 200
        })
        break
      }
    }
  },

  tapMove() {
    this.setData({
      scrollTop: this.data.scrollTop + 10
    })
  },

  //商品单选
  checkboxbind(e){ 
    var t=this
    console.log(e.currentTarget.dataset.id)
    
    t.data.goodsCarLists.forEach(element => {
      if(element.id==e.currentTarget.dataset.id){
        if(element.checked==true){
          element.checked=false
          t.setData({
            isselectshop:t.data.isselectshop-1,
            shoptotal:t.data.shoptotal-element.goodsPrice*element.goodsNum
          })
        }else{
          element.checked=true
          t.setData({
            isselectshop:t.data.isselectshop+1,
            shoptotal:t.data.shoptotal+element.goodsPrice*element.goodsNum
          })
        }
    }
    });
    t.setData({
      goodsCarLists:t.data.goodsCarLists
    })
    if(t.data.goodsCarLists.some(item=>item.checked==false)){
      this.setData({
        isselect:false
      })
    }else{
      this.setData({
        isselect:true
      })
    }
    console.log(t.data.goodsCarLists)
  },
  //购物车无产品时
  goclass(){
    wx.switchTab({
      url: '/pages/index/index',
    })

  },
  //商品全选
  selectall(e){
    this.setData({
      shoptotal:0
     })

    this.setData({
      isselect:!this.data.isselect
    })
    if(this.data.isselect==true){
      this.setData({
         isselectshop:this.data.goodsCarLists.length
        })
    this.data.goodsCarLists.forEach(element => {
      element.checked=true
      this.setData({
        shoptotal:this.data.shoptotal+element.goodsPrice*element.goodsNum
       })
    });
   }else{
    this.setData({
      isselectshop:0
     })
    this.data.goodsCarLists.forEach(element => {
      element.checked=false
      this.setData({
        shoptotal:0
       })
    });
   }
   this.setData({
    goodsCarLists:this.data.goodsCarLists
   })
  },
  add(e){
    var t=this
    console.log(e.currentTarget.dataset.goodsnum+'dssdf'+e.currentTarget.dataset.goodsstock)
    if(e.currentTarget.dataset.goodsnum < e.currentTarget.dataset.goodsstock){
      wx.showLoading({
        title: '请稍等',
        mask:true
      })
     
      t.operateGoodsCar(e.currentTarget.dataset.id,1)
      
    }else{
      wx.showToast({
        title: '库存不够了',
        icon:'none'
      })

    }
    
    
    
  },
  reduce(e){
    var t=this
    console.log(e)
    
    if (e.currentTarget.dataset.goodsnum==1) {
      wx.showModal({
        title:'提示',
        content:'您将删除该商品',
        success:function(res){
          if (res.confirm) {
            wx.showLoading({
              title: '请稍等',
              mask:true
            })
            t.operateGoodsCar(e.currentTarget.dataset.id,2)
          }else if(res.cancel){
          }
        }
      })
    }else{
      wx.showLoading({
        title: '请稍等',
        mask:true
      })
      t.operateGoodsCar(e.currentTarget.dataset.id,2)
    }
    
  },
  bindinput(e){
    // console.log(e)
    // this.setData({
    //   total:e.detail.value
    // })
  },
  bindblur(e){
    if(e.detail.value<1){
      this.setData({
        total:1
      })
    }
  },
  //操作购物车增加或者减少Type=1增加Type=2减少
  operateGoodsCar(goodIds,Type){
    var t=this
    wx.request({
      url: app.globalData.Interfaceurl + 'operateGoodsCar',
      method: "post",
      header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
          userId: app.globalData.userId,
          goodsCarId:goodIds,
          operateType:Type,
      },
      success: res => {
          console.log(res)
          console.log('0',t.data.goodsCarLists)
          if (Type==1) {
            var goodscarlistnun=[]
             t.data.goodsCarLists.forEach((element,index) => {
              if (element.id==goodIds) {
                
                element.goodsNum=element.goodsNum+1
              }
              goodscarlistnun[index]=element
            });
            console.log('1',goodscarlistnun)
            
          }else if(Type==2){
            var goodscarlistnun=[]
            t.data.goodsCarLists.forEach((element,index) => {
              if (element.id==goodIds) { 
                if(element.goodsNum>1)  {
                  element.goodsNum=element.goodsNum-1   
                  goodscarlistnun.push(element)   
                }              
              }else{
                goodscarlistnun.push(element) 
              }
              
              
            });
           
          }
          console.log('goodscarlistnun',goodscarlistnun)

          t.setData({
            goodsCarLists:goodscarlistnun,
          })
          wx.hideLoading()
         
      }
     })
  },
  //去购物车支付
  gocartpay(){
    var shoplist=[]
    this.data.goodsCarLists.forEach((element,index)=> {
      if(element.checked==true){
         shoplist.push(element)
      }
      
    });
    console.log(shoplist)
    if(shoplist.length>0){
      let goodIds=[]
      this.data.goodsCarLists.forEach((item,index)=>{
        goodIds.push(item.id)
      })

    wx.navigateTo({
      url: '/pages/porder/porder?type=1&shoplist='+JSON.stringify(shoplist)+'&carttotal='+this.data.shoptotal,
    })
  }else{
    wx.showToast({
      title: '您还没选择要付款的商品',
      icon:'none',
      duration:2000
    })
  }
  },
  delGoodsCar(e){

    var t=this
    wx.showModal({
      title:'删除',
      cancelColor: 'cancelColor',
      content: '是否删除此商品',
      showCancel:true,
      cancelText:'我再想想',
      confirmText:'确认删除',
      success (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.Interfaceurl + 'delGoodsCar',
            method: "post",
            header: {
                "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
            },
            data: {
                userId: app.globalData.userId,
                goodsCarIds:e.currentTarget.dataset.id
            },
            success: res => {
                console.log(res)
                if(res.data.result==0&&res.statusCode==200){
                  wx.showToast({
                    title: '删除成功',
                    icon:"success",
                    duration:2000,
                  })
                  t.setData({
                    pageNo:1,
                    goodsCarLists:[]
                  })
                  t.getGoodsCadList()
                }else(
                  wx.showToast({
                    title: '操作失败，请重试',
                    icon:'error',
                    duration:2000,
                  })
                )
                
            }
           })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
     
  },

  //选择框选择
  checkboxChange(e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    const items = this.data.items
    const values = e.detail.value
    this.setData({
      items
    })
  },
  //去授权
  gologin(){
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.pageScrollTo({
      scrollTop:0,
      duration: 0,
    })
    if (wx.getStorageSync('userInfo')=='') {

      console.log("未登录")
      wx.hideLoading()
      this.setData({
        islogins:true,
        ishave:false,
        isfeli:false,
        isloding:false,
        isempty:false
      })
      
    }else{
      wx.showLoading({
        title: '请稍等',
        mask:true
      })
      this.setData({
        islogins:false,
        pageNo:1,
        goodsCarLists:[],
        isselectshop:0
      })
      this.getGoodsCadList()     
    }
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    this.getTabBar().setData({
      selected: 2,
      show:true,
    })
  }
  this.setData({
    isselect:false,
    shoptotal:0,
  })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('1111')
    if (wx.getStorageSync('userInfo')!='') {
      
    
    if(this.data.pageNo<this.data.pagemax){
      this.setData({
        pageNo:this.data.pageNo+1
      })
      this.getGoodsCadList()
    }
  }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return share.share()
  }
})